Basic Usage
Defined in:
addon/index.js:27
Models
The first thing we need to do it build our validation rules. This will then generate a Mixin that you will be able to incorporate into your model or object.
// models/user.js
import Ember from 'ember';
import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';
const Validations = buildValidations({
username: validator('presence', true),
password: [
validator('presence', true),
validator('length', {
min: 4,
max: 8
})
],
email: [
validator('presence', true),
validator('format', { type: 'email' })
],
emailConfirmation: [
validator('presence', true),
validator('confirmation', {
on: 'email',
message: '{description} do not match',
description: 'Email addresses'
})
]
});
Once our rules are created and our Mixin is generated, all we have to do is add it to our model.
// models/user.js
export default DS.Model.extend(Validations, {
'username': attr('string'),
'password': attr('string'),
'email': attr('string')
});
Objects
You can also use the generated Validations
mixin on any Ember.Object
or child
of Ember.Object
, like Ember.Component
. For example:
// components/x-foo.js
import Ember from 'ember';
import { validator, buildValidations } from 'ember-cp-validations';
const Validations = buildValidations({
bar: validator('presence', true)
});
export default Ember.Component.extend(Validations, {
bar: null
});
To lookup validators, container access is required which can cause an issue with Ember.Object
creation if the object is statically imported. The current fix for this is as follows.
// models/user.js
export default Ember.Object.extend(Validations, {
username: null
});
Ember < 2.3.0-beta.1
// routes/index.js
import User from '../models/user';
export default Ember.Route.extend({
model() {
var container = this.get('container');
return User.create({ username: 'John', container })
}
});
Ember >= 2.3.0-beta.2
// routes/index.js
import User from '../models/user';
export default Ember.Route.extend({
model() {
return User.create(
Ember.getOwner(this).ownerInjection(),
{ username: 'John' }
);
}
});